package cc.cc4414.crtc.webSocket;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author cc 2018年10月26日
 */
@Component
@ServerEndpoint("/webSocket/{userId}")
public class WebSocket {

	private static final Logger log = LoggerFactory.getLogger(WebSocket.class);

	private Session session;

	private String userId;

	private static Map<String, WebSocket> map = new ConcurrentHashMap<String, WebSocket>();

	@OnOpen
	public void onOpen(Session session, @PathParam("userId") String userId) {
		this.session = session;
		this.userId = userId;
		map.put(userId, this);
		log.info("【websocket消息】有新的连接, 用户id:{}", this.userId);
	}

	@OnClose
	public void onClose() {
		if (this.userId != null) {
			map.remove(this.userId);
			log.info("【websocket消息】连接断开, 用户id:{}", this.userId);
		}
	}

	public void sendMessage(String message, String userId) {
		WebSocket webSocket = map.get(userId);
		if (webSocket == null) {
			log.error("对方未连接");
			return;
		}
		try {
			synchronized (webSocket) {
				webSocket.session.getBasicRemote().sendText(message);
			}
		} catch (IOException e) {
			log.error("发送消息失败", e);
		}
	}

}
